package net.swissbite.VolumeCallPriceCalc;

/**
 * Copyright (C) 2011  David Daester
 * 
 * This file is part of VolumeCallPriceCalc.
 *
 * VolumeCallPriceCalc is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * VolumeCallPriceCalc is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with VolumeCallPriceCalc.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.swissbite.VolumeCallPriceCalc.models.IdDurNumbModel;
import net.swissbite.VolumeCallPriceCalc.utils.DurationFormater;
import net.swissbite.VolumeCallPriceCalc.utils.KeyListGenerator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.TextView;

/**
 * Starting activity. Still in heavy development.
 * 
 * At the moment: Displays a list of every outgoing call grouped by month, sum
 * of calls and duration within a month.
 * 
 * What it should do is not yet clear, it's primarly used for testing what I can
 * do with android and {@link android.provider.CallLog.Calls}.
 * 
 * @author David Däster
 * 
 */
public class VolumeCallPriceCalcActivity extends Activity {
	/** Called when the activity is first created. */

	static final int DIALOG_ORDERING_ID = 0;

	private int OrderingMenu = 0;
	private static final String ORDER_ID_KEY = "ORDER_ID";
	private KeyListGenerator klg;

	@Override
	public Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case DIALOG_ORDERING_ID:

			CharSequence[] checkBoxItems = getResources().getStringArray(
					R.array.groupBy_items);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.groupBy_title);
			builder.setSingleChoiceItems(checkBoxItems, OrderingMenu,
					new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(
									VolumeCallPriceCalcActivity.this,
									VolumeCallPriceCalcActivity.class);
							intent.putExtra(ORDER_ID_KEY, which);
							startActivity(intent);
							finish();
							dialog.dismiss();

						}
					});
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem mSettings = menu.add(getString(R.string.menu_settings));
		MenuItem mRefresh = menu.add(getString(R.string.menu_refresh));
		mRefresh.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem item) {
				Intent intent = new Intent(VolumeCallPriceCalcActivity.this,
						VolumeCallPriceCalcActivity.class);
				intent.putExtra(ORDER_ID_KEY, OrderingMenu);
				startActivity(intent);
				finish();
				return true;
			}
		});
		MenuItem mOrdering = menu.add(getString(R.string.menu_ordering));
		mOrdering.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem item) {
				VolumeCallPriceCalcActivity.this.showDialog(DIALOG_ORDERING_ID);
				return true;
			}
		});
		return true;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.klg = new KeyListGenerator();
		klg.updateData(createCursor());
		setContentView(R.layout.main);

		this.OrderingMenu = getResources()
				.getInteger(R.integer.orderby_default);
		Bundle b = getIntent().getExtras();
		if (b != null) {
			OrderingMenu = b.getInt(ORDER_ID_KEY,
					getResources().getInteger(R.integer.orderby_default));
		}

		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setMovementMethod(new ScrollingMovementMethod());
		if (!klg.isEmpty()) {
			switch (OrderingMenu) {
			case 0:
				HashMap<String, List<IdDurNumbModel>> numbDur = klg
						.getAsNumberMap();
				String[] numbKeys = new String[numbDur.keySet().size()];
				numbDur.keySet().toArray(numbKeys);
				Arrays.sort(numbKeys);
				for (String key : numbKeys) {
					tv.append(key + ":\n");
					for (IdDurNumbModel val : numbDur.get(key)) {
						tv.append("\t"
								+ val.getMonth()
								+ "/"
								+ val.getYear()
								+ ": "
								+ DurationFormater.secondsToHMMSS(val
										.getDuration()) + " ->#"
								+ val.getCounts() + "\n");

					}
				}
				break;
			case 1:
				HashMap<Date, List<IdDurNumbModel>> dateDurNum = klg
						.getAsDateMap();
				Date[] dateKeys = new Date[dateDurNum.keySet().size()];
				dateDurNum.keySet().toArray(dateKeys);
				Arrays.sort(dateKeys);
				// They are ASC sorted. We need it otherwise.
				for (int i = dateKeys.length - 1; i >= 0; i--) {
					Date dkey = dateKeys[i];
					long monthDuration = 0;
					StringBuilder innerString = new StringBuilder();
					for (IdDurNumbModel val : dateDurNum.get(dkey)) {
						innerString
								.append("\t")
								.append(val.getIdentifier())
								.append(": ")
								.append(DurationFormater.secondsToHMMSS(val
										.getDuration())).append(" ->#")
								.append(val.getCounts()).append("\n");
						monthDuration += val.getDuration();

					}

					tv.append(dkey.getMonth() + "/" + (dkey.getYear() + 1900)
							+ ": " + dateDurNum.get(dkey).size() + " Calls; "
							+ DurationFormater.secondsToHMMSS(monthDuration)
							+ "\n");
					tv.append(innerString.toString());
				}
				break;
			case 2:
				HashMap<Integer, List<IdDurNumbModel>> countsDurNum = klg
						.getAsCountsMap();
				Integer[] countKeys = new Integer[countsDurNum.keySet().size()];
				countsDurNum.keySet().toArray(countKeys);
				Arrays.sort(countKeys);
				for (int i = countKeys.length - 1; i >= 0; i--) {
					Integer ckey = countKeys[i];
					tv.append("Counts: " + ckey + "\n");
					for (IdDurNumbModel val : countsDurNum.get(ckey)) {
						tv.append("\t"
								+ val.getIdentifier()
								+ " - "
								+ val.getMonth()
								+ "/"
								+ val.getYear()
								+ ": "
								+ DurationFormater.secondsToHMMSS(val
										.getDuration()) + "\n");

					}

				}
				break;
			default:
				tv.append("Unkown ordering type...");
				break;
			}
		} else {
			tv.append(getResources().getString(R.string.emptyWelcome));
		}
	}

	private Cursor createCursor() {
		Cursor c = getContentResolver().query(
				android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
				android.provider.CallLog.Calls.DATE + " DESC");

		startManagingCursor(c);
		return c;
	}
}